//
//  ITDownloaderManager.m
//  InduceTool
//
//  Created by 魏延龙 on 2020/9/10.
//  Copyright © 2020 魏延龙. All rights reserved.
//

#import "ITDownloaderManager.h"
#import "ITDownloader.h"
@interface ITDownloaderManager ()
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@end

@implementation ITDownloaderManager
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.operationQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static id sharedManager = nil;
    dispatch_once(&onceToken, ^{
        sharedManager = [[[self class] alloc] init];
        [sharedManager setOperationQueueName:@"TCBlobDownloadManager_SharedInstance_Queue"];
    });
    return sharedManager;
}

- (ITDownloader *)startDownloadWithURLStr:(NSString *)urlstr
                                   toPath:(nonnull NSString *)path
                                 progress:(nonnull void (^)(uint64_t, uint64_t, NSInteger, float))progressBlock
                                    error:(nonnull void (^)(NSError *_Nonnull))errorBlock
                                 complete:(nonnull void (^)(BOOL, NSString *_Nonnull))completeBlock {
    for (ITDownloader *blob in [self.operationQueue operations]) {
        if ([blob.name isEqualToString:urlstr]) {
            if (blob.state == ITDownloaderDownloading) {
                return blob;
            }
        }
    }

    ITDownloader *downloader = [[ITDownloader alloc] initWithUrl:urlstr
                                                          toPath:path
                                                        progress:progressBlock
                                                           error:errorBlock
                                                        complete:completeBlock];
    [downloader setName:urlstr];
    [self.operationQueue addOperation:downloader];
    return downloader;
}

- (void)cancleWithUrl:(NSString *)url {
    for (ITDownloader *blob in [self.operationQueue operations]) {
        if ([blob.name isEqualToString:url]) {
            [blob cancel];
        }
    }
}

- (void)cancleAll {
    for (ITDownloader *blob in [self.operationQueue operations]) {
        [blob cancel];
    }
}

- (void)cancelWithUrl:(NSString *)urlstr {
    for (ITDownloader *blob in [self.operationQueue operations]) {
        if ([blob.name isEqualToString:urlstr]) {
            [blob cancel];
        }
    }
}

#pragma mark - Custom Setters
- (void)setOperationQueueName:(NSString *)name
{
    [self.operationQueue setName:name];
}

@end
